import { Injectable } from '@nestjs/common';
import * as Sequelize from 'sequelize'; // 引入 Sequelize 库
import { ResultData } from 'src/utils/result';
import * as db_context  from '../../database/sequelize'; // 引入 Sequelize 实例
import { makeSalt, encryptPassword } from '../../utils/cryptogram'; // 引入加密函数


@Injectable()
export class UserService {
  async findOne(username: string): Promise<any | undefined> {
    const sql = `
    SELECT
      *
    FROM
    user
    WHERE
    username = '${username}'
  `; // 一段平淡无奇的 SQL 查询语句
  try {
    const user = (await db_context.sequelize.query(sql, {
      type: Sequelize.QueryTypes.SELECT, // 查询方式
      raw: true, // 是否使用数组组装的方式展示结果
      logging: true, // 是否将 SQL 语句打印到控制台
    }))[0];
    // 若查不到用户，则 user === undefined
    return user;
  } catch (error) {
    console.error(error);
    return void 0;
  }
}


  /**
   * 注册
   * @param requestBody 请求体
   */
   async register(requestBody: any): Promise<any> {
    const { accountName, realName, password, repassword, mobile } = requestBody;
    if (password !== repassword) {
      return ResultData.fail(400,`两次密码输入不一致`)
     
    }
    const user = await this.findOne(accountName);
    console.log(user);
    if (user) {
      return ResultData.fail(400,`用户已存在`)
      
    }
    const salt = makeSalt(); // 制作密码盐
    const hashPwd = encryptPassword(password, salt);  // 加密密码
    try {

      const item: any = {
        name: realName,
        username:accountName,
        passwdSalt:salt,
        password:hashPwd,
        mobile:mobile
      };
      await db_context.User.createItem < db_context.User > (item);
      return ResultData.ok("Success")
      
    } catch (error) {

     return ResultData.fail(503,`Service error: ${error}`)
     
    }
  }
}